package com.itmayiedu.api.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.activemq.command.ActiveMQQueue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.itmayiedu.api.service.MemberService;
import com.itmayiedu.base.BaseApiService;
import com.itmayiedu.base.BaseRedisService;
import com.itmayiedu.base.ResponseBase;
import com.itmayiedu.constants.Constants;
import com.itmayiedu.dao.MemberDao;
import com.itmayiedu.entity.UserEntity;
import com.itmayiedu.mq.RegisterMailboxProducer;
import com.itmayiedu.utils.MD5Util;
import com.itmayiedu.utils.TokenUtils;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
public class MemberServiceImpl extends BaseApiService implements MemberService{
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private RegisterMailboxProducer registerMailboxProducer;
	@Value("${messages.queue}")
	private String MESSAGESQUEUE;	
	@Override
	public ResponseBase findUserById(Long userId) {
		UserEntity user = memberDao.findById(userId);
		if(user==null) {
			return setResultError("未查找到用户信息。");
		}
		return setResultSuccess(user);
	}
	@Override
	public ResponseBase registerUser(@RequestBody UserEntity userEntity) {
		//参数验证
		String password = userEntity.getPassword();
		if (StringUtils.isEmpty(password)) {
			return setResultMsg("密码不能为空");
		}
		//加密
		String newpassword= MD5Util.MD5(password);
		userEntity.setPassword(newpassword);
		userEntity.setCreated(new Date());
		userEntity.setUpdated(new Date());
		Integer result = memberDao.insertUser(userEntity);
		if (result<=0) {
			return setResultError("注册用户信息失败");
		}
		String email=userEntity.getEmail();
		String json=emailJson(email);
		log.info("#####会员服务推送消息到服务平台json:{}",json);
		sendMsg(json);
		return setResultMsg("用户注册成功");
	}
	private String emailJson(String email) {
		JSONObject jsonObject = new JSONObject();
		JSONObject header = new JSONObject();
		header.put("interfaceType", Constants.MSG_EMAIL);
		JSONObject content = new JSONObject();
		content.put("email", email);
		jsonObject.put("header",header);
		jsonObject.put("content",content);
		
		return jsonObject.toJSONString();
	}
	private void sendMsg(String json) {
		ActiveMQQueue activeMQQueue = new ActiveMQQueue(MESSAGESQUEUE);
		registerMailboxProducer.sendMsg(activeMQQueue, json);

	}
	@Override
	public ResponseBase login(@RequestBody UserEntity user) {
		// 1.验证参数
		String username = user.getUsername();
		if (StringUtils.isEmpty(username)) {
			return setResultError("用戶名称不能为空!");
		}
		String password = user.getPassword();
		if (StringUtils.isEmpty(password)) {
			return setResultError("密码不能为空!");
		}
		// 2.数据库查找账号密码是否正确
		String newPassWrod = MD5Util.MD5(password);
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("username",username);
		map.put("password",newPassWrod);
		UserEntity userEntity = memberDao.login(map);//运行到这里报错
		
		return setLogin(userEntity);
	}
	//封装代码
	private ResponseBase setLogin(@RequestBody UserEntity userEntity) {
//		
//		if(userEntity.getToken()!=null) {
//			String token = userEntity.getToken();
//			//redis删除token
//			//baseRedisService.delKey(token);
//			//这里应该做什么？生成一个新的token--没写
//		}
		if (userEntity == null) {
			return setResultError("账号或者密码不正确");
		}
		// 3.如果账号密码正确，对应生成token
		String memberToken = TokenUtils.getMemberToken();
		if(StringUtils.isEmpty(userEntity.getToken()))
		{
			Map<String,Object> map1 = new HashMap<String, Object>();
			map1.put("id",userEntity.getId());
			map1.put("token", memberToken);
			memberDao.addToken(map1);
		}
		// 4.存放在redis中，key为token value 为 userid
		Integer userId = userEntity.getId();
		log.info("####用户信息token存放在redis中... key为:{},value", memberToken, userId);
		baseRedisService.setString(memberToken, userId + "", Constants.TOKEN_MEMBER_TIME);
		// 5.直接返回token
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("memberToken", memberToken);
		return setResultSuccess(jsonObject);		
	}
	@Override
	public ResponseBase findByTokenUser(@RequestParam("token") String token) {
		//1.验证参数
		if(StringUtils.isEmpty(token))
		{
			return setResultError("token不能为空");
		}
		//2.从redis中使用 token 查找对应userid
		String strUserId =baseRedisService.getString(token);
		if(StringUtils.isEmpty(strUserId)) {
			return setResultError("token无效或者已过期");
		}
		Long userId=Long.parseLong(strUserId);
		//3.使用userid去数据库查询用 户信息返回给客户端
		UserEntity userEntity = memberDao.findById(userId);
		if(userEntity==null) {
			return setResultError("未查找到用户信息");
		}
		userEntity.setPassword(null);
		return setResultSuccess(userEntity);
	}
	//作业：如何只能让一个用户登陆，在数据库中添加一个token字段
	@Override
	public ResponseBase findByOpenIdUser(@RequestParam("openid") String openid) {
		//1.验证参数
		if(StringUtils.isEmpty(openid)) {
			return setResultError("openid不能为空");
		}
		//2.使用openid查询数据库user表对应的user信息
		UserEntity userEntity = memberDao.findByOpenIdUser(openid);
		if(userEntity==null) {
			return setResultError(Constants.HTTP_RES_CODE_201,"未关联用户，请关联");
		}
		//3.自动登陆
		
		return setLogin(userEntity);
	}
	@Override
	public ResponseBase qqLogin(@RequestBody UserEntity userEntity) {
		//1.验证参数
		String openid = userEntity.getOpenid(); 
		if(StringUtils.isEmpty(openid)) {
			return setResultError("openid不能为空");
		}
		ResponseBase setLogin = login(userEntity);
		if(!setLogin.getCode().equals(Constants.HTTP_RES_CODE_200 )) {
			return setLogin;
		}
		//2.先进行账号登陆，如果登陆成功,数据库修改对应openid
		JSONObject jsonObjet = (JSONObject) setLogin.getData();
		String memberToken = jsonObjet.getString("memberToken");
		ResponseBase findByTokenUser = findByTokenUser(memberToken);
		if(!findByTokenUser.getCode().equals(Constants.HTTP_RES_CODE_200)) {
			return findByTokenUser;
		}
		UserEntity userEntity2 = (UserEntity) findByTokenUser.getData();
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("id",userEntity2.getId());
		map.put("openid", openid);
		Integer updateByOpenIdUser = memberDao.updateByOpenIdUser(map);
		if(updateByOpenIdUser<=0) {
			return setResultError("qq账号关联失败 ");
		}
		return setLogin;
	}
}
